package com.furentech.iotserver.fa.utils;

import java.io.*;

public class FileUtils {
    public static long getFileSizeInBytes(String fileName) {
        File file = new File(fileName);

        if (file.exists() && file.isFile()) {
            return file.length();
        } else {
            return 0;
        }
    }
    public static int readFromFile(byte[] resByteBuf,String fileName,long from ,int length){

        long  to=from+length-1;

        long fileLength=getFileSizeInBytes(fileName);

        if (to > ( fileLength)) {
            to = fileLength;
        }

        for (int i = 0; i < length; i++) {
            resByteBuf[i] = 0;
        }

        try{
            FileInputStream fis = new FileInputStream(fileName);

            BufferedInputStream bis=new BufferedInputStream(fis);
            if(from!=0) {
                bis.skip(from - 1);
            }

            bis.read(resByteBuf, 0, (int)(to-from+1));
        }catch(FileNotFoundException e){
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }

        return (int)(to-from+1);
    }
}
